package com.visionet.waveletData.web.webservice.rest;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.visionet.waveletData.web.common.utilities.props.PropsKeys;
import com.visionet.waveletData.web.common.utilities.props.PropsUtil;

import org.springside.modules.mapper.JsonMapper;

@Component
public abstract class BaseRest {
    private static Log log = LogFactory.getLog(BaseRest.class);
    protected static JsonMapper mapper = JsonMapper.nonDefaultMapper();
    
	public static final int PAGE_SIZE = 10;
	
	//这里是集成环境的路径，不能修改它，如果要修改，请在initUlr设置本机的路径
	protected static String SEARCHER_URL = PropsUtil.getProperty(PropsKeys.SEARCHER_SOLR_URL);
	protected static String SMS_URL = PropsUtil.getProperty(PropsKeys.SMS_HTTP_URL);
	private  RestTemplate jdkTemplate;
	protected  RestTemplate httpClientRestTemplate;
	private  HttpComponentsClientHttpRequestFactory httpClientRequestFactory;
	// 设置处理HttpBasic Header的Interceptor
	protected ClientHttpRequestInterceptor interceptor = null;

	
	protected RestTemplate getRestTemplate(){
		return httpClientRestTemplate;
	}

	
	/**
	 * 这个方法用来设置登录用户信息
	 */
	public abstract void initUser();
	
	protected void setUser(ClientHttpRequestInterceptor interceptor){
		this.interceptor = interceptor;
	}
	
	@PostConstruct
	public  void initResource(){
		
		// 默认使用JDK Connection
		jdkTemplate = new RestTemplate();
		// (optional)设置20秒超时
		((SimpleClientHttpRequestFactory) jdkTemplate.getRequestFactory()).setConnectTimeout(20000);

		// 设置使用HttpClient4.0
		httpClientRestTemplate = new RestTemplate();
		httpClientRequestFactory = new HttpComponentsClientHttpRequestFactory();
		// (optional)设置20秒超时
		httpClientRequestFactory.setConnectTimeout(20000);

		httpClientRestTemplate.setRequestFactory(httpClientRequestFactory);
//		initUser();
//		if(interceptor==null){
//			throw new RuntimeException("not initial User");
//		}else{
//			httpClientRestTemplate.setInterceptors(Lists.newArrayList(interceptor));
//		}
		
	}
	
	@PreDestroy
	public void close(){
		try {
			// 退出时关闭HttpClient4连接池中的连接
			httpClientRequestFactory.destroy();
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
		
		
	}

	
}
